<#
    .SYNOPSIS
    批量下载文件，避免重复下载

    .DESCRIPTION

    .INPUTS
    None.

    .OUTPUTS
    None.

    .EXAMPLE
    PS> .ps1

    .LINK
    Online version: 
#>
    
# 输入参数
param (
    [Switch] $Uninstall = $False
)


# 环境变量配置 
$DownSaveDir = "${env:USERPROFILE}\Downloads";# 下载存放位置变量
# $DownSaveDir = "C:\Tools\pyenv" # 下载存放位置变量

$OsVersion = 0;
# 获取操作系统信息
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$version = [version]$os.Version
# Windows 7 对应版本号为 6.1.*（例如 6.1.7601）。
# Windows 10/11 对应版本号为 10.0.*（例如 10.0.19045）。
# 判断系统版本
# 判断系统版本
if ($version.Major -eq 6) {
    switch ($version.Minor) {
        1 { # 6.1.*
            # Write-Output "Windows 7" 
            $OsVersion = 7;
        }       
        2 { # 6.2.*
            # Write-Output "Windows 8" 
            $OsVersion = 8;
        }       
        3 { # 6.3.*
            # Write-Output "Windows 8.1" 
            $OsVersion = 8.1;
        }    
        default { 
            # Write-Output "其他 Windows 版本: $($os.Caption)" 
            $OsVersion = 0;
        }
    }
} elseif ($version.Major -eq 10) {
    # 通过构建号区分 Win10 和 Win11
    if ($version.Build -ge 22000) {          # Win11 构建号 ≥ 22000
        # Write-Output "Windows 11"
        $OsVersion = 11;
    } else {                                 # Win10 构建号 < 22000
        # Write-Output "Windows 10"
        $OsVersion = 10;
    }
} else {
    # Write-Output "未知系统: $($os.Caption)"
    $OsVersion = 0;
}



# 函数 添加系统环境变量
Function Add-EnvVars($AddEnvName,$AddEnvVal,$AddEnvClass) {
                                           # Process 、User 、Machine
    # 检查是否已经存在
    # ## 检查环境变量
    # if(-Not ($env:PATH.Contains("C:\Tools\bin"))) {
    #     echo 'C:\Tools\bin not in path, appending environment variable'
    #     # $env:PATH += ";C:\Tools\bin\";
    # }
    # if(-Not ($env:PATH.Contains("C:\Tools\PSTools"))) {
    #     echo 'C:\Tools\PSTools not in path, appending environment variable'
    #     # $env:PATH += ";C:\Tools\PSTools\";
    # }
    # 获取原来的环境变量
    # $ProcessPathParts = [System.Environment]::GetEnvironmentVariable('PATH', "Process") -Split ";"
    # Write-Host "[INFO] $ProcessPathParts"; # 打印信息
    # $UserPathParts = [System.Environment]::GetEnvironmentVariable('PATH', "User") -Split ";"
    # Write-Host "[INFO] $UserPathParts"; # 打印信息
    # $SysPathParts = [System.Environment]::GetEnvironmentVariable('PATH', "Machine") -Split ";"
    # Write-Host "[INFO] $SysPathParts"; # 打印信息
    # $PathParts = [System.Environment]::GetEnvironmentVariable("${AddEnvName}", "${AddEnvClass}") -Split ";"
    $OrgPathParts = [System.Environment]::GetEnvironmentVariable("${AddEnvName}", "${AddEnvClass}")
    $PathParts = $OrgPathParts -Split ";"
    Write-Host "[INFO] $PathParts"; # 打印信息
    if($PathParts -contains $AddEnvVal) { # 已存在了
       # -contains操作符确实很强大，但是很遗憾，它不能在指定字符串中包含通配符。如果想使用通配符进行查找数组元素，则可以使用-like操作符。
        Write-Host "[INFO] $PathParts  exist $AddEnvVal"; # 打印信息
    } else { # 不存在
        # 
        # Write-Host "[INFO] $AddEnvName isn't exist $AddEnvVal"; # 打印信息
        $NewPathParts = $PathParts + $AddEnvVal
        # Write-Host "[INFO] PathParts = $PathParts "; # 打印信息
        $NewPath = $NewPathParts -Join ";"
        # Write-Host "[INFO] NewPath == $NewPath  "; # 打印信息
        # [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${AddEnvVal}",  "${AddEnvClass}")
        # [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${NewPath}",  "${AddEnvClass}")
        # [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${NewPath}",  "Machine") # 系统环境变量无法使用脚本写入 ，提示不允许所请求的注册表访问权。”
        # 添加完再次查询
        $PathParts = [System.Environment]::GetEnvironmentVariable("${AddEnvName}", "${AddEnvClass}") -Split ";"
        Write-Host "[INFO] $PathParts"; # 打印信息
    }

}
# 函数 下载
function Invoke-Download
{
    param (
        [Parameter()] [string] $uri = "https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.$m2/conus/hrrr.t$m21z.wrfsfcf00.grib2.idx",
        [Parameter()] [string] $outputPath = "C:\OpenGrADS-2.2\data\hrrr\test.grb2",
        [Parameter()] [int] $sleeptimer = 30,
        [Parameter()] [int] $maxTries = 3,
        [Parameter()] [int] $tries = 0
    )
    # Write-Host "[Debug] This is Invoke-Download(). $uri --> $outputPath" # 打印信息
    # 判断是否下载完成存在文件，存在则则不重复下载
    $TRUE_FALSE=(Test-Path $outputPath)
    if($TRUE_FALSE -eq "True")
    {
        # 文件已经存在
        echo "[Info] $outputPath already exists." 
    } else {
        try
        {
            Invoke-WebRequest -Uri $uri -OutFile $outputPath;
        }
        catch [System.Net.WebException]
        {
            $tries++;

            if($tries -lt $maxTries)
            {
                Start-Sleep -Seconds $sleeptimer
                Invoke-Download -uri $uri -outputPath $outputPath -sleeptimer $sleeptimer -maxTries $maxTries -tries $tries
            }
            else
            {
                Write-Error ("Tried to download '{0}' {1}-times and failed" -f $uri, $tries);
            }
        }
    }
}

# 函数 
Function Download-Url-File($downloadUrl) {
    # Write-Host "[Debug] This is Download-Url-File(). "; # 打印信息;
    $saveFileName = $downloadUrl.split("/")[-1];
    $outputPath = "$DownSaveDir/$saveFileName";
    Write-Host "[INFO] The [ $downloadUrl ] file is being downloaded now. "; # 打印信息
    Invoke-Download $downloadUrl $outputPath;
    Write-Host "[INFO] The [ $downloadUrl ] file is downloaded and stored in [$outputPath]."; # 打印信息
}

# 函数 下载主要函数入口
Function DownloadMain() {
    # 
    # $githubProxyUrl = "https://github.moeyy.xyz/"
    $githubProxyUrl = ""

    # 下载python环境
    # 注： python 3.8.9 是最后支持windows7的版本
    # Write-Host "[Debug] This is Main(). "; # 打印信息;
    $downloadUrl = 'https://mirrors.huaweicloud.com/python/3.8.9/python-3.8.9-amd64.exe';
    Download-Url-File $downloadUrl;
    $downloadUrl = 'https://mirrors.huaweicloud.com/python/3.10.9/python-3.10.9-amd64.exe';
    Download-Url-File $downloadUrl;

    # 下其他工具
    ## 下载工具： Neat-Download-Manager
    # [Neat Download Manager](https://neatdownload.com/)
    # https://github.com/Neatdownloadmanager/Neat-Download-Manager/releases
    $downloadUrl = 'https://www.neatdownloadmanager.com/file/NeatDM_setup.exe';
    Download-Url-File $downloadUrl;

    ## 阅读器
    ### koodo-reader
    # https://github.com/koodo-reader/koodo-reader
    $downloadUrl = "${githubProxyUrl}https://github.com/koodo-reader/koodo-reader/releases/download/v1.8.7/Koodo-Reader-1.8.7-Portable.exe";
    Download-Url-File $downloadUrl;
    ### Readest
    $downloadUrl = "${githubProxyUrl}https://github.com/readest/readest/releases/download/v0.9.23/Readest_0.9.23_x64-portable.exe";
    Download-Url-File $downloadUrl;

    ## 显示当前网速、CPU及内存利用率的桌面悬浮窗软件
    # https://github.com/zhongyang219/TrafficMonitor
    $downloadUrl = "${githubProxyUrl}/https://github.com/zhongyang219/TrafficMonitor/releases/download/V1.85.1/TrafficMonitor_V1.85.1_x64.zip";
    Download-Url-File $downloadUrl;
    
    ## freefilesync
    # 下载地址：https://freefilesync.org/download.php
    $downloadUrl = 'https://freefilesync.org/download/FreeFileSync_14.2_Windows_Setup.exe';
    Download-Url-File $downloadUrl;

    # syncthing
    # https://syncthing.net/
    # https://github.com/syncthing/syncthing
    $downloadUrl = "${githubProxyUrl}https://github.com/syncthing/syncthing/releases/download/v1.29.3/syncthing-windows-amd64-v1.29.3.zip";
    Download-Url-File $downloadUrl;

    ## localSend
    # [LocalSend - 下载](https://localsend.org/zh-CN/download)
    # https://github.com/localsend/localsend
    if ($OsVersion -eq 7) {
        #LocalSend-1.15.4-windows-x86-64_win7
        $downloadUrl = "${githubProxyUrl}https://github.com/localsend/localsend/releases/download/v1.15.4/LocalSend-1.15.4-windows-x86-64.exe";
        Download-Url-File $downloadUrl;
    } else {
        $downloadUrl = 'https://d.localsend.org/LocalSend-1.17.0-windows-x86-64.exe';
        Download-Url-File $downloadUrl;
    }

    ## Lua
    # $downloadUrl = 'https://nchc.dl.sourceforge.net/project/luabinaries/5.4.2/Windows Libraries/Dynamic/lua-5.4.2_Win64_dll17_lib.zip?viasf=1'
    # Download-Url-File $downloadUrl;
    # [GitHub - rjpcomputing/luaforwindows](https://github.com/rjpcomputing/luaforwindows)
    $downloadUrl = "${githubProxyUrl}https://github.com/rjpcomputing/luaforwindows/releases/download/v5.1.5-52/LuaForWindows_v5.1.5-52.exe";
    Download-Url-File $downloadUrl;

    # 下载Git
    # https://git-scm.com/downloads
    $downloadUrl = "${githubProxyUrl}https://github.com/git-for-windows/git/releases/download/v2.49.0.windows.1/Git-2.49.0-64-bit.exe";
    Download-Url-File $downloadUrl;

    # btrfs 
    # WinBtrfs-适用于Windows的开源btrfs驱动程序
    $downloadUrl = "${githubProxyUrl}https://github.com/maharmstone/btrfs/releases/download/v1.9/btrfs-1.9.zip";
    Download-Url-File $downloadUrl;
    $downloadUrl = "${githubProxyUrl}https://github.com/maharmstone/btrfs/releases/download/v1.9/btrfs-1.9-pdb.zip";
    Download-Url-File $downloadUrl;

    # 7-zip
    $downloadUrl = 'https://www.7-zip.org/a/7z2409-x64.exe';
    Download-Url-File $downloadUrl;

    # deskflow
    # [GitHub - deskflow/deskflow: .](https://github.com/deskflow/deskflow)
    if ($OsVersion -eq 7) {
        #
    } else {
        $downloadUrl = "${githubProxyUrl}https://github.com/deskflow/deskflow/releases/download/v1.20.1/deskflow-1.20.1-win-x64.msi";
        Download-Url-File $downloadUrl;
    }

    # 截图 + 贴图 Snipaste
    # [Snipaste - 截图 + 贴图](https://zh.snipaste.com/)
    $downloadUrl = 'https://download.snipaste.com/archives/Snipaste-2.10.6-x64.zip';
    Download-Url-File $downloadUrl;

    # 截图 + 贴图 ShareX
    # [GitHub - ShareX/ShareX:](https://github.com/ShareX/ShareX)
    # $downloadUrl = "${githubProxyUrl}/https://github.com/ShareX/ShareX/releases/download/v17.0.0/ShareX-17.0.0-portable.zip';
    $downloadUrl = "${githubProxyUrl}https://github.com/ShareX/ShareX/releases/download/v17.0.0/ShareX-17.0.0-setup.exe";
    Download-Url-File $downloadUrl;

    # 多功能超实用小工具 PowerToys
    # [GitHub - microsoft/PowerToys](https://github.com/microsoft/PowerToys)
    if ($OsVersion -eq 7) {
        #
    } else {
        $downloadUrl = "${githubProxyUrl}/https://github.com/microsoft/PowerToys/releases/download/v0.89.0/PowerToysSetup-0.89.0-x64.exe";
        Download-Url-File $downloadUrl;
    }
    # DevToys
    # [GitHub - DevToys-app/DevToys: A Swiss Army knife for developers.](https://github.com/DevToys-app/DevToys)
    $downloadUrl = "${githubProxyUrl}https://github.com/DevToys-app/DevToys/releases/download/v1.0.13.0/64360VelerSoftware.DevToys_1.0.13.0_neutral_._j80j2txgjg9dj.msixbundle";
    Download-Url-File $downloadUrl;

    #  MPV-EASY Player 
    $downloadUrl = "${githubProxyUrl}https://github.com/422658476/MPV-EASY-Player/releases/download/0.39.0.3/MPV-EASY.Player.V0.39.0.3.exe";
    Download-Url-File $downloadUrl;
    ## 如果是win7版本安装后需要 替换mpv版 mpv-x86_64-20200105-git-9eb3991
    # [mpv.io | Installation](https://mpv.io/installation/)
    # [mpv Old Versions Downloads - VideoHelp](https://www.videohelp.com/software/mpv-media-player/old-versions)
    if ($OsVersion -eq 7) {
        $downloadUrl = 'https://www.videohelp.com/download/mpv-x86_64-20200105-git-9eb3991.7z';
        Download-Url-File $downloadUrl;
    } else {
        # 
    }
    # MusicPlayer2
    # [MusicPlayer2一款可以播放常见音频格式的音频播放器。](https://github.com/zhongyang219/MusicPlayer2)
    if ($OsVersion -eq 7) {
        # 支持win的版本是 V2.73
        $downloadUrl = 'https://gitee.com/zhongyang219/MusicPlayer2/releases/download/V2.73/MusicPlayer2_V2.73_x64.zip';
        Download-Url-File $downloadUrl;
    } else {
        $downloadUrl = "${githubProxyUrl}https://github.com/zhongyang219/MusicPlayer2/releases/download/V2.77.1/MusicPlayer2_V2.77.1_x64.zip";
        Download-Url-File $downloadUrl;
    }


    # Mp3tag
    # [Mp3tag - the universal Tag Editor (ID3v2, MP4, OGG, FLAC, ...)](https://www.mp3tag.de/en/)
    $downloadUrl = 'https://download.mp3tag.de/mp3tagv328-x64-setup.exe'
    Download-Url-File $downloadUrl;

    # 漫画阅读器 YACReader
    # [YACReader - Github](https:///github.com/YACReader/yacreader)
    $downloadUrl = "${githubProxyUrl}https://github.com/YACReader/yacreader/releases/download/9.15.0/YACReader-v9.15.0.2501014-winx64-7z.exe";
    # $downloadUrl = "${githubProxyUrl}/https://github.com/YACReader/yacreader/releases/download/9.15.0/YACReader-v9.15.0.2501014-winx64-7z-qt6.exe";
    Download-Url-File $downloadUrl;

    # 数据恢复软件·俄 R.saver
    # [R.saver – бесплатная программа для восстановления данных](https://rlab.ru/tools/rsaver.html)
    $downloadUrl = 'https://rlab.ru/download/R.saver.zip'
    Download-Url-File $downloadUrl;

    # 视频格式转换 HandBrake
    # [HandBrake - Github](https://github.com/HandBrake)
    $downloadUrl = "${githubProxyUrl}https://github.com/HandBrake/HandBrake/releases/download/1.9.2/HandBrake-1.9.2-x86_64-Win_GUI.exe";
    Download-Url-File $downloadUrl;
    $downloadUrl = "${githubProxyUrl}https://github.com/HandBrake/HandBrake/releases/download/1.9.2/HandBrakeCLI-1.9.2-win-x86_64.zip";
    Download-Url-File $downloadUrl;

    # 录屏 obs-studio
    # [GitHub - obsproject/obs-studio: OBS Studio ](https://github.com/obsproject/obs-studio)
    $downloadUrl = "${githubProxyUrl}https://github.com/obsproject/obs-studio/releases/download/31.0.2/OBS-Studio-31.0.2-Windows-Installer.exe";
    Download-Url-File $downloadUrl;

    # Notepad--
    # https://github.com/cxasm/notepad--
    $downloadUrl = "${githubProxyUrl}https://github.com/cxasm/notepad--/releases/download/notepad-v3.1/Notepad--v3.1.0-plugin-Installer.exe";
    Download-Url-File $downloadUrl;

    # vscode
    # [GitHub - microsoft/vscode: Visual Studio Code](https://github.com/microsoft/vscode)
    if ($OsVersion -eq 7) {
        # VSCodeUserSetup-x64-1.70.2
        # https://code.visualstudio.com/updates/v1_72
        # https://update.code.visualstudio.com/1.72.2/win32-x64-user/stable
        $downloadUrl = 'https://vscode.download.prss.microsoft.com/dbazure/download/stable/d045a5eda657f4d7b676dedbfa7aab8207f8a075/VSCodeUserSetup-x64-1.72.2.exe'
        Download-Url-File $downloadUrl;
    } else {
        $downloadUrl = 'https://vscode.download.prss.microsoft.com/dbazure/download/stable/ddc367ed5c8936efe395cffeec279b04ffd7db78/VSCodeUserSetup-x64-1.98.2.exe';
        Download-Url-File $downloadUrl;
    }

    # Steam++ 、Watt Toolkit
    # [瓦特工具箱(Steam++官网) - Watt Toolkit](https://steampp.net/)
    $downloadUrl = 'https://gitee.com/rmbgame/SteamTools/releases/download/3.0.0-rc.15/Steam%20%20_v3.0.0-rc.15_win_x64.exe'
    Download-Url-File $downloadUrl;

#     - [GnuWin - Browse /sed at SourceForge.net](https://sourceforge.net/projects/gnuwin32/files/sed/)
#         - [windows - sed  ](https://udomain.dl.sourceforge.net/project/gnuwin32/sed/4.2.1/sed-4.2.1-bin.zip)
#     - [GnuWin - Browse /gawk at SourceForge.net](https://sourceforge.net/projects/gnuwin32/files/gawk/)
#         - [windows - gawk ](https://udomain.dl.sourceforge.net/project/gnuwin32/gawk/3.1.6-1/gawk-3.1.6-1-bin.zip)
#     - [GnuWin - Browse /grep at SourceForge.net](https://sourceforge.net/projects/gnuwin32/files/grep/)
#         - [windows - grep ](https://udomain.dl.sourceforge.net/project/gnuwin32/grep/2.5.4/grep-2.5.4-setup.exe)
#         - [windows - grep ](https://udomain.dl.sourceforge.net/project/gnuwin32/grep/2.5.4/grep-2.5.4-1-bin.zip)

    # 时钟锁屏
    if ($OsVersion -eq 7) {
        # Windows7 下适中锁屏 FlipIt.scr
        # [GitHub - phaselden/FlipIt: Flip Clock screensaver](https://github.com/phaselden/FlipIt)
        $downloadUrl = "${githubProxyUrl}https://github.com/phaselden/FlipIt/releases/download/v1.3/FlipIt.scr";
        Download-Url-File $downloadUrl;
    } else {
        # win10/11 时钟锁屏
        # [Fliqlo - Flip Clock App and Screensaver](https://fliqlo.com/)
        $downloadUrl = "https://fliqlo.com/download/FliqloScr.zip";
        Download-Url-File $downloadUrl;
    }

    #  激活工具
    if ($OsVersion -eq 7) {
        # 
        # [GitHub - grub4dos/ntloader: bootloader for NT6+ WIM, VHD and VHDX images](https://github.com/grub4dos/ntloader)

        # OEM工具只支持MBR环境下的OEM激活，在GPT环境下就不能用

        # Microsoft_Toolkit
        $downloadUrl = "${githubProxyUrl}https://github.com/bouletmarc/Microsoft_Toolkit/archive/master.zip";
        Download-Url-File $downloadUrl;
        # EzWindSLIC - 易于使用的OEM：适用于Windows Vista/7/Server 2008（R2）/2012（R2）/2016/2019/2022的SLP激活器
        # [GitHub - Dir3ctr1x/EzWindSLIC](https://github.com/Dir3ctr1x/EzWindSLIC)
        $downloadUrl = "${githubProxyUrl}https://github.com/Dir3ctr1x/EzWindSLIC/releases/download/v3.62f/EzWindSLIC_3.62f_traditional.zip";
        Download-Url-File $downloadUrl;
        $downloadUrl = "${githubProxyUrl}https://github.com/Dir3ctr1x/EzWindSLIC/releases/download/v3.62f/EzWindSLIC_3.62f_AIO.cmd";
        Download-Url-File $downloadUrl;
        # [盘点时下各大Windows/Office激活工具 - 哔哩哔哩](https://www.bilibili.com/opus/562331031462206854)
    } else {
        # 
    }
    # [GitHub - zbezj/HEU_KMS_Activator](https://github.com/zbezj/HEU_KMS_Activator)
    $downloadUrl = "${githubProxyUrl}https://github.com/zbezj/HEU_KMS_Activator/releases/download/50.0.0/HEU_KMS_Activator_v50.0.0.rar";
    Download-Url-File $downloadUrl;
    
}

# 函数 设置环境变量主要程序入口
Function SetEnvMain() {
    Add-EnvVars "PATH" "C:\Tools\PSTools" "User";
    Add-EnvVars "PATH" "C:\Tools\bin" "User";
    Add-EnvVars "PATH" "${env:USERPROFILE}\Documents\XWorkSpaces\my-windows-config\scripts\fsshscp" "User";
}

# 函数 
Function Main() {
    SetEnvMain
    # DownloadMain
}

# 开始
Main
